﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace TestProject
{
    class XMLDemo
    {
        public void ReadTest()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"..\data\sample.xml");

            XmlNode xn = doc.SelectSingleNode("part");
            foreach (XmlNode character in xn.ChildNodes)
            {
                Console.WriteLine($"---------- Character ---------");
                foreach (XmlAttribute catt in character.Attributes)
                {
                    Console.WriteLine(catt.Name + "=" + catt.Value);
                }

                foreach (XmlNode data in character.ChildNodes)
                {
                    Console.WriteLine($"---------- Character.Data ---------");
                    foreach (XmlAttribute datt in data.Attributes)
                    {
                        Console.WriteLine(datt.Name + "=" + datt.Value);
                    }
                }
            }
        }

        public void WriteTest()
        {
            XmlDocument doc = new XmlDocument();  
            XmlElement xn = doc.CreateElement("part");//创建part节点
            // 插入doc
            doc.AppendChild(xn); 
            // 在首行插入XML的版本和编码信息。
            doc.InsertBefore(doc.CreateXmlDeclaration("1.0", "UTF-8", ""), xn);


            xn.SetAttribute("K1001", "P305-1"); // 设置属性
            xn.SetAttribute("K1002", "Tranfom1");

            for (int i = 0; i < 3; i++)
            {
                XmlElement sub_i = doc.CreateElement("Characteristic");
                sub_i.SetAttribute("K2001", i + "");//设置该节点genre属性
                sub_i.SetAttribute("K2002", "Parameter" + i);//设置该节点ISBN属性
                for (int j = 0; j < 5; j++)
                {
                    XmlElement sub_ij = doc.CreateElement("Data");
                    sub_ij.SetAttribute("K0001", "3.1415");//设置该节点genre属性
                    sub_ij.SetAttribute("K0004", "2019/3/29 15:23:45");//设置该节点ISBN属性
                    sub_i.AppendChild(sub_ij);
                }

                xn.AppendChild(sub_i);
            }

            doc.Save("test.xml");
        }

    }
}
